﻿#region USINGS
using System;
using System.Data;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using DevComponents.DotNetBar.Controls;
using PolePositionDesktop.WebService;
using GoogleEarthClasses.Entities;
using GoogleEarthClasses.Global;
using GoogleEarthClasses.Logic;
using System.Configuration;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Net;
#endregion USINGS

namespace PolePositionDesktop
{   
    public partial class AreasControl : UserControl
    {
        protected List<EPolygonType> m_ServerPolygonTypes;
        DataTable m_PolygonsTable;
        DataTable m_PolygonsTypesTable;
        #region FORM EVENTS
        public AreasControl()
        {
            InitializeComponent();
        }
        private void AreasControl_Resize(object sender, EventArgs e)
        {
            this.dataGridViewPolygons.Size = new Size(this.dataGridViewPolygons.Size.Width, this.Height);
        }

        private void AreasControl_Load(object sender, EventArgs e)
        {
            //DownloadServerPolygonTypes();
        }
        private void dataGridViewPolygons_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            dataGridViewPolygons.CommitEdit(DataGridViewDataErrorContexts.Commit);
            dataGridViewPolygons.UpdateCellValue(dataGridViewPolygons.Columns["PolygonSelected"].Index, dataGridViewPolygons.SelectedRows[0].Index);
        }
        #endregion FORM EVENTS
        #region POLYGON TYPES AND POLYGONS TABLES
        public void DownloadServerPolygonTypes()
        {
            Server _Server = new Server();
            _Server.LoadServerPolygonTypes();
            m_ServerPolygonTypes = _Server.PolygonTypes;
            bindingSourcePolygons.DataSource = GetPolygons("");
            LoadDropDownAreaType();
        }
        private void bindingSourcePolygons_DataSourceChanged_1(object sender, EventArgs e)
        {
            dataGridViewPolygons.DataSource = bindingSourcePolygons;
            dataGridViewPolygons.Update();
        }
        private void LoadDropDownAreaType() {
            string _TypeName;
            foreach (DataRow dr in m_PolygonsTypesTable.Rows) { 
                _TypeName = dr["TypeName"].ToString();
                DropDownAreaType.Items.Add((object)_TypeName);
            }
        }

        /// <summary>
        /// METHOD THAT GETS BACK A COMPLETE LIST OF POLYGONS FOR A SPECIFIED TYPENAME
        /// IF TypeName == "" THEN IT RETURNS ALL OF THE POLYGONS IN THE LIST
        /// </summary>
        private DataTable GetPolygons(string TypeName)
        {
            #region CREATE POLYGONS TYPE TABLE STRUCTURE
            m_PolygonsTypesTable = new DataTable();
            m_PolygonsTypesTable.Columns.Add(new DataColumn("TypeName", typeof(string)));
            #endregion CREATE POLYGONS TYPE TABLE STRUCTURE
            #region CREATE POLYGONS TABLE STRUCTURE
            m_PolygonsTable = new DataTable();
            m_PolygonsTable.Columns.Add(new DataColumn("PolygonId", typeof(int)));
            m_PolygonsTable.Columns.Add(new DataColumn("PolygonSelected", typeof(bool)));
            m_PolygonsTable.Columns.Add(new DataColumn("PolygonName", typeof(string)));
            m_PolygonsTable.Columns.Add(new DataColumn("TypeName", typeof(string)));
            #endregion CREATE POLYGONS TABLE STRUCTURE

            DataRow row;
            foreach (EPolygonType m_SelectedPolygonTypeTemp in m_ServerPolygonTypes)
            {
                if (m_SelectedPolygonTypeTemp.TypeName == TypeName || TypeName == "")
                {
                    #region GENERATE POLYGONS TYPE TABLE TO LOAD DROPDOWN
                    row = m_PolygonsTypesTable.NewRow();
                    row["TypeName"] = m_SelectedPolygonTypeTemp.TypeName;
                    m_PolygonsTypesTable.Rows.Add(row);
                    #endregion GENERATE POLYGONS TYPE TABLE TO LOAD DROPDOWN
                    
                    #region GENERATE POLYGONS TABLE TO LOAD DATAGRID VIEW
                    foreach (EPolygon m_PolygonTemp in m_SelectedPolygonTypeTemp.Polygons)
                    {
                        row = m_PolygonsTable.NewRow();
                        row["PolygonId"] = m_PolygonTemp.PolygonId;
                        row["PolygonSelected"] = true;
                        row["PolygonName"] = m_PolygonTemp.Name;
                        row["TypeName"] = m_PolygonTemp.TypeName;
                        m_PolygonsTable.Rows.Add(row);
                    }
                    #endregion GENERATE POLYGONS TABLE TO LOAD DATAGRID VIEW
                }
            }
            return m_PolygonsTable;
        }
        #endregion POLYGON TYPES AND POLYGONS TABLES
        

        #region VIEW POLYGONS ON KML
        public void ViewPolygons(bool m_ShowPolygons, ref List<EKmlFile> m_KMLItems)
        {
            if (m_ShowPolygons && m_ServerPolygonTypes != null)
            {
                foreach (EPolygonType _PolygonType in m_ServerPolygonTypes)
                {
                    m_KMLItems.Add(GESetNewPolygonTypeStyle(_PolygonType));
                    foreach (EPolygon _Polygon in _PolygonType.Polygons)
                    {
                        if (IsPolygonSelected(_Polygon.PolygonId))
                            m_KMLItems.Add(GESetNewPolygon(_Polygon));
                    }
                }
            }
            else
            {
                GEHelper.ClearPolygonTypes(ref m_KMLItems);
            }
        }
        private bool IsPolygonSelected(int PolygonId)
        {
            foreach (DataRow dr in m_PolygonsTable.Rows)
            {
                if (ConvertHelper.Toint(dr[dataGridViewPolygons.Columns["PolygonId"].Index]) == PolygonId)
                    return ConvertHelper.Tobool(dr[dataGridViewPolygons.Columns["PolygonSelected"].Index]);
            }
            return false;
        }
        
        /// <summary>
        /// ADDS A NEW POLYGON TYPE STYLE TO THE EKmlFile LIST, INCLUDING A FIELD WITH THE COMPLETE KML CODE
        /// </summary>
        private EKmlFile GESetNewPolygonTypeStyle(EPolygonType _PolygonType)
        {
            
            string _Code;
            _Code = GEHelper.GeneratePolygonTypeStyle(_PolygonType);
            return new EKmlFile(TypeKMLOfElement.Style, _PolygonType.TypeName, _Code);
            
        }
        /// <summary>
        /// ADDS A NEW POLYGON TO THE EKmlFile LIST, INCLUDING A FIELD WITH THE COMPLETE KML CODE
        /// </summary>
        private EKmlFile GESetNewPolygon(EPolygon _Polygon)
        {
            string _Code;
            _Code = GEHelper.GeneratePolygon(_Polygon);
            return new EKmlFile(TypeKMLOfElement.Polygon, _Polygon.PolygonId.ToString(), _Code);
        }
        #endregion VIEW POLYGONS ON KML
        #region POLYGON LOAD DETAILS
        private void dataGridViewPolygons_SelectionChanged(object sender, EventArgs e)
        {
            DataGridView _DataGridSelected = (DataGridView)sender;
            EPolygon _Polygon = null;
            if (_DataGridSelected.SelectedRows.Count <= 0)
                return;
            //CleanDetails();
            Int32 m_SelectedPolygonId;
            m_SelectedPolygonId = Convert.ToInt32(_DataGridSelected["PolygonId", _DataGridSelected.SelectedRows[0].Index].Value);
            _Polygon = GetCurrentPolygon(m_SelectedPolygonId);
            if (_Polygon != null)
                LoadDetails(_Polygon);
        }
        private void CleanDetails() {
            txtName.Text = "";
            txtPolygonId.Text = "";
            txtPoints.Text = "";
            if(DropDownAreaType.Items.Count>0)
                DropDownAreaType.SelectedItem = DropDownAreaType.Items[0];
           // DropDownAreaType.SelectedIndex = 1;
        }
        private EPolygon GetCurrentPolygon(Int32 SelectedPolygonId) {
            foreach (EPolygonType _PolygonType in m_ServerPolygonTypes)
            {
                foreach (EPolygon _Polygon in _PolygonType.Polygons)
                {
                    if (_Polygon.PolygonId == SelectedPolygonId)
                        return _Polygon;
                }
            }
            return null;
        }
        private void LoadDetails(EPolygon Polygon) {
            txtPolygonId.Text = Polygon.PolygonId.ToString();
            txtName.Text = Polygon.Name;
            txtPoints.Text = Polygon.Points;
            DropDownAreaType.Text = Polygon.TypeName;
        }
        #endregion POLYGON LOAD DETAILS
        #region POLYGON ADD, EDIT & REMOVE

        private void buttonSave_Click(object sender, EventArgs e)
        {
            Int32 m_PolygonId = Int32.Parse(txtPolygonId.Text);
            foreach (EPolygonType m_PolygonTypeTemp in m_ServerPolygonTypes)
            {
                foreach (EPolygon m_PolygonTemp in m_PolygonTypeTemp.Polygons)
                {
                    if (m_PolygonTemp.PolygonId == m_PolygonId)
                    {
                        //SET VALUES ON EXISTING LIST
                        m_PolygonTemp.Name = txtName.Text;
                        m_PolygonTemp.Points = txtPoints.Text;
                        m_PolygonTemp.TypeName = DropDownAreaType.Text;
                        UpdatePolygonOnServer(m_PolygonTemp);

                        //UPDATE POLYGON VALUES ON SERVER
                        UpdatePolygonOnServer(m_PolygonTemp);

                        //UPDATE GRID
                        bindingSourcePolygons.DataSource = GetPolygons("");
                    }
                }
            }
        }
        private void UpdatePolygonOnServer(EPolygon Polygon)
        {
            Service1 WebServer = new Service1();
            WebServer.PolygonUpdate(Polygon.PolygonId,
                                    Polygon.UpdatedBy,
                                    Polygon.UpdatedAt,
                                    "",
                                    Polygon.Name,
                                    Polygon.TypeName,
                                    Polygon.Points,
                                    Polygon.Description);
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            Int32 m_PolygonId = Int32.Parse(txtPolygonId.Text);
            foreach (EPolygonType m_PolygonTypeTemp in m_ServerPolygonTypes)
            {
                foreach (EPolygon m_PolygonTemp in m_PolygonTypeTemp.Polygons)
                {
                    if (m_PolygonTemp.PolygonId == m_PolygonId)
                    {
                        //UPDATE POLYGON VALUES ON SERVER
                        Service1 WebServer = new Service1();
                        WebServer.PolygonDelete(m_PolygonTemp.PolygonId);

                        //SET VALUES ON EXISTING LIST
                        m_PolygonTypeTemp.Polygons.Remove(m_PolygonTemp);

                        //UPDATE GRID
                        bindingSourcePolygons.DataSource = GetPolygons("");

                        return;
                    }
                }
            }
        }

        private void buttonNewArea_Click(object sender, EventArgs e)
        {
            EPolygon Polygon = new EPolygon();
            Polygon.Name = txtName.Text;
            Polygon.Points = txtPoints.Text;
            Polygon.TypeName = DropDownAreaType.Text;
                        
            foreach (EPolygonType m_PolygonTypeTemp in m_ServerPolygonTypes)
            {
                if (m_PolygonTypeTemp.TypeName == Polygon.TypeName) {
                    //UPDATE POLYGON VALUES ON SERVER
                    Service1 WebServer = new Service1();
                    Polygon.PolygonId = WebServer.PolygonInsert("",
                                            "",
                                            Polygon.UpdatedBy,
                                            Polygon.UpdatedAt,
                                            "",
                                            Polygon.Name,
                                            Polygon.TypeName,
                                            Polygon.Points,
                                            Polygon.Description);

                    //SET VALUES ON EXISTING LIST
                    m_PolygonTypeTemp.Polygons.Add(Polygon);

                    //UPDATE GRID
                    bindingSourcePolygons.DataSource = GetPolygons("");
                    return;
                }
            }
        }
        #endregion POLYGON ADD, EDIT & REMOVE
    }
}
